package com.navinfo.collect.library.data.datahandler

import android.content.Context
import android.os.Handler
import android.os.Looper
import com.navinfo.collect.library.data.DataConversion
import com.navinfo.collect.library.data.dao.impl.MapLifeDataBase
import com.navinfo.collect.library.data.entity.CustomLayerItem
import com.navinfo.collect.library.data.entity.DataLayerItemType
import com.navinfo.collect.library.data.entity.LayerManager
import com.navinfo.collect.library.utils.MoshiUtil
import kotlin.concurrent.thread

/**
 * 数据库操作
 */


open class DataLayerHandler(context: Context, dataBase: MapLifeDataBase) :
    BaseDataHandler(context, dataBase) {

    /**
     * 根据json创建数据库
     * [
     * {"key":"name","type":"TEXT","nullable":true},
     * {"key":"address","type":"TEXT","nullable":true},
     * {"key":"type","type":"INTEGER","nullable":false},
     * {"key":"longitude","type":"REAL","nullable":false},
     * {"key":"latitude","type":"REAL","nullable":false},
     * {"key":"id","type":"INTEGER","nullable":false,"primaryKey":true}
     * ]
     *
     *
     *  _db.execSQL("CREATE TABLE IF NOT EXISTS `edit_pois` (`rowId` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT, `postCode` TEXT, `address` TEXT, `kindCode` TEXT, `uuid` TEXT, `geometry` TEXT, `maxx` REAL NOT NULL, `minx` REAL NOT NULL, `maxy` REAL NOT NULL, `miny` REAL NOT NULL)");
    _db.execSQL("CREATE TABLE IF NOT EXISTS `element` (`rowId` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `display_style` TEXT, `display_text` TEXT, `start_level` INTEGER NOT NULL, `end_level` INTEGER NOT NULL, `zindex` INTEGER NOT NULL, `visibility` INTEGER NOT NULL, `operation_time` TEXT, `export_time` TEXT, `t_lifecycle` INTEGER NOT NULL, `t_status` INTEGER NOT NULL, `bundle` TEXT, `uuid` TEXT, `geometry` TEXT, `maxx` REAL NOT NULL, `minx` REAL NOT NULL, `maxy` REAL NOT NULL, `miny` REAL NOT NULL)");
    _db.execSQL("CREATE TABLE IF NOT EXISTS `layerElement` (`rowId` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `uuid` TEXT, `layer_uuid` TEXT, `element_uuid` TEXT)");
    _db.execSQL("CREATE TABLE IF NOT EXISTS `layerManager` (`rowId` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `uuid` TEXT, `layer_name` TEXT, `zindex` INTEGER NOT NULL, `visibility` INTEGER NOT NULL, `export_time` TEXT, `import_time` TEXT, `bundle` TEXT)");
    _db.execSQL("CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)");
    _db.execSQL("INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '7a041262c922535fc32b56d4dd16ea92')");
     *
     */

    fun createTable(
        layer: LayerManager,
        list: List<CustomLayerItem>,
        callback: (res: Boolean, errorString: String) -> Unit
    ) {
        thread(start = true) {
            try {
                val sql = StringBuffer();
                sql.append("CREATE TABLE IF NOT EXISTS '${layer.id}' ( uuid TEXT NOT NULL, ")
                for (i in list.indices) {
                    if (i > 0) {
                        sql.append(", ")
                    }
                    sql.append("'${list[i].key}' ")
                    sql.append(layerItemTypeToDBType(list[i].type))
                    if (list[i].primaryKey) {
                        sql.append(" PRIMARY KEY AUTOINCREMENT NOT NULL ")
                    } else if (!list[i].nullable) {
                        sql.append(" NOT NULL")
                    }
                }
                sql.append(")")
                layer.bundle = MoshiUtil.toJson(list);
                layer.bundle = DataConversion.layerItemsToJson(list)
                mDataBase.layerManagerDao.insert(layer)
                mDataBase.openHelper.writableDatabase.execSQL(sql.toString())
                Handler(Looper.getMainLooper()).post {
                    callback.invoke(true, "")
                }
            } catch (e: Throwable) {
                Handler(Looper.getMainLooper()).post {
                    callback.invoke(false, "${e.message}")
                }
            }

        }
    }


    /**
     * 将字段的控件类型，转换成数据库字段类型
     *
     * enum LayerItemType {
    ///输入框
    layerItemTypeInput,

    ///输入框集合
    layerItemTypeInputArray,

    ///纯展示文本
    layerItemTypeText,

    ///单选框
    layerItemTypeSingleSelection,

    ///多选框
    layerItemTypeMultipleSelection
    }
     */
    private fun layerItemTypeToDBType(type: DataLayerItemType): String {
        when (type) {
            DataLayerItemType.DataLayerItemTypeInput -> return "TEXT"
        }
        return "TEXT";
    }


    /**
     * 查询获取图层列表
     */
    fun getDataLayerList(callback: (list: List<LayerManager>) -> Unit) {
        thread(start = true) {
            val list = mDataBase.layerManagerDao.findList();
            Handler(Looper.getMainLooper()).post {
                callback.invoke(list)
            }
        }
    }

    /**
     * 查询某个获取图层
     */
    fun getDataLayer(layerId: String, callback: (layer: LayerManager) -> Unit) {
        thread(start = true) {
            val layer = mDataBase.layerManagerDao.findLayerManager(layerId);
            Handler(Looper.getMainLooper()).post {
                callback.invoke(layer)
            }
        }
    }
}